/*
	*@brief				:读写锁的初始化，加锁与解锁

	*@param[rwlock]		:rwlock 指向需要进行初始化或销毁的读写锁对象

	*@param[attr]		:可将参数 attr 设置为 NULL，表示使用属性的默认值来初始化条件变量，PTHREAD_RWLOCK_INITIALIZER 这种方式初始化，而不同之处在于，使用宏不进行错误检查。

	*@return 			:成功返回 0；失败将返回一个非 0 的错误码。
	*@others			:PTHREAD_PROCESS_SHARED： 共享读写锁。该读写锁可以在多个进程中的线程之间共享；
						 PTHREAD_PROCESS_PRIVATE： 私有读写锁。只有本进程内的线程才能够使用该读写锁，这是读写锁共享属性的默认值
*/

/*
	int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
	int pthread_rwlock_init(pthread_rwlock_t *rwlock, const pthread_rwlockattr_t *attr);
	int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
	int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
	int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
	int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
	int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
	int pthread_rwlockattr_getpshared(const pthread_rwlockattr_t *attr, int *pshared);
	int pthread_rwlockattr_setpshared(pthread_rwlockattr_t *attr, int pshared);
*/



#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>

static pthread_rwlock_t rwlock; //定义读写锁对象
static int g_count = 0;

static void *read_thread(void *arg)
{
	int number = *((int *)arg);
	int j;

	for (j = 0; j < 5; j++)
	{
		pthread_rwlock_rdlock(&rwlock); //以读模式获取锁
		printf("读线程<%d>, g_count=%d\n", number + 1, g_count);
		pthread_rwlock_unlock(&rwlock); //解锁
		sleep(1);
	}
	return (void *)0;
}

static void *write_thread(void *arg)
{
	int number = *((int *)arg);
	int j;

	for (j = 0; j < 5; j++)
	{
		pthread_rwlock_wrlock(&rwlock); //以写模式获取锁
		printf("写线程<%d>, g_count=%d\n", number + 1, g_count += 20);
		pthread_rwlock_unlock(&rwlock); //解锁
		sleep(1);
	}
	return (void *)0;
}

static int nums[5] = {0, 1, 2, 3, 4};

int main(int argc, char *argv[])
{
	pthread_t tid[10];
	int ret;
	int i;

	/* 初始化读写锁*/
	pthread_rwlock_init(&rwlock, NULL);

	/* 创建 5 个读 g_count 变量的线程 */
	for (i = 0; i < 5; i++)
	{
		pthread_create(&tid[i], NULL, read_thread, &nums[i]);
	}

	/* 创建 5 个写 g_count 变量的线程 */
	for (i = 0; i < 5; i++)
	{
		pthread_create(&tid[i + 5], NULL, write_thread, &nums[i]);
	}

	/* 等待线程结束 */
	for (i = 0; i < 10; i++)
	{
		pthread_join(tid[i], NULL);
	}

	/* 销毁读写锁 */
	pthread_rwlock_destroy(&rwlock);
	exit(0);
}